import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { NoteEntity } from '../entities/note.entity';

@Injectable()
export class NoteService {
  constructor(
    @InjectRepository(NoteEntity)
    private readonly noteRepository: Repository<NoteEntity>,
  ) {}

  //查询全部
  async findAll(): Promise<NoteEntity[]> {
    return await this.noteRepository.find();
  }
  //根据id查找
  async getTitleById(id: number) {
    const result = await this.noteRepository.find({
      where: { id: id },
    });
    return result ?? 'byId not found';
  }

  //插入一条记录
  async addOneRecord(id: number, title: string, content: string) {
    const result = await this.noteRepository
      .createQueryBuilder()
      .insert()
      .into(NoteEntity)
      .values([{ id: id, title: title, content: content }])
      .execute();
    if (result.raw.affectedRows === 1) {
      return { code: 200, msg: 'success' };
    } else {
      return { code: 500, msg: 'fail' };
    }
  }
}
